package com.ls.fw.index.solr.client.dao.base.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.solr.client.solrj.SolrServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.solr.core.SolrOperations;
import org.springframework.data.solr.core.SolrTemplate;

import com.ls.fw.index.solr.client.dao.base.BaseSolrDao;
import com.ls.fw.index.solr.client.dao.base.BaseSolrGenericDao;

@NoRepositoryBean
public class BaseSolrGenericDaoImpl<T, PK extends Serializable> extends BaseIndexSolrDaoImpl implements BaseSolrGenericDao<T, PK> {
	
	/**
	 * 日志，可用于子类
	 */
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	
	
	/**
	 * Sping jpa data实现的基础操作
	 */
	private BaseSolrDao<T,PK> baseSolrDao = null;
	
	private SolrOperations solrOperations;

	/**
	 * 实体类类型(由机关办法主动赋值)
	 */
	private Class<T> entityClass = null;

	/**
     * 
     */
	@SuppressWarnings("unchecked")
	public BaseSolrGenericDaoImpl() {
		this.entityClass = null;
		Class<?> c = getClass();
		Type t = c.getGenericSuperclass();
		if (t instanceof ParameterizedType) {
			Type[] p = ((ParameterizedType) t).getActualTypeArguments();
			this.entityClass = (Class<T>) p[0];
		}
		if(this.baseSolrDao==null && this.solrOperations!=null){
			baseSolrDao = new BaseSolrDaoImpl<T,PK>(this.solrOperations,this.entityClass);
		}
	}
	
	public Class<T> getEntityClass() {
		return this.entityClass;
	}
	 
	@Override
	public BaseSolrDao<T,PK> getBaseSolrDao() {
		return baseSolrDao;
	}
	
	public void setBaseSolrDao(BaseSolrDao<T,PK> baseSolrDao) {
		this.baseSolrDao = baseSolrDao;
	}

	@Autowired
	public void setSolrOperations(SolrOperations solrOperations) {
		this.solrOperations = solrOperations;
		if(this.baseSolrDao==null && this.solrOperations!=null){
			baseSolrDao = new BaseSolrDaoImpl<T,PK>(this.solrOperations,this.entityClass);
		}
		try{
			this.setServer((this.solrOperations.getSolrServer()));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public SolrOperations getSolrOperations() {
		return solrOperations;
	}
	
	
	/**
	 * 改变collection
	 * @param name
	 */
	@Override
	public SolrServer switchName(String name){
		this.solrOperations = new SolrTemplate(super.switchName(name));
		return solrOperations.getSolrServer();
	}
	
	@Override
	public SolrServer switchServer(String baseUrl,String name){
		this.solrOperations = new SolrTemplate(super.switchServer(baseUrl,name));
		return solrOperations.getSolrServer();
	}
	
	@Override
	public SolrServer switchServer(String baseUrl){
		this.solrOperations = new SolrTemplate(super.switchServer(baseUrl));
		return solrOperations.getSolrServer();
	}
}
